<template>
  <ul
    class="fixed top-1/2 right-0 w-16 flex flex-col items-center bg-white rounded-l-xl shadow-lg z-50 transform -translate-y-1/2 transition-all duration-300"
    :class="{ 'translate-x-0': isVisible }">
    <li v-for="item in navItems" :key="item.path" @click="navigateTo(item.path)"
      class="flex flex-col items-center justify-center h-16 w-full border-b border-gray-100 last:border-0 group relative hover:bg-red-500 hover:text-white transition-colors duration-200"
      :class="{ 'bg-red-500 text-white': isActive(item.path) }">
      <el-icon :size="24" class="mb-1 group-hover:scale-110 transition-transform duration-200">
        <component :is="item.icon" />
      </el-icon>
      <div class="text-xs font-medium">{{ item.label }}</div>

      <!-- 数字角标 -->
      <span v-if="item.badge"
        class="absolute top-1 right-1 bg-red-400 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">
        {{ orderCount }}
      </span>
    </li>

    <li v-show="scrollY > 300" @click="scrollToTop"
      class="flex flex-col items-center justify-center h-16 w-full border-t border-gray-100 bg-gray-50 hover:bg-red-500 hover:text-white transition-colors duration-200">
      <el-icon size="24" class="mb-1">
        <Top />
      </el-icon>
      <div class="text-xs font-medium">回顶部</div>
    </li>
  </ul>
</template>

<script setup>
import { getCartCountApi } from '@/apis/cart';
import { getOrderCountApi } from '@/apis/order';
import { onMounted, onUnmounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

// 导航项配置
const navItems = ref([
  { path: '/index', icon: 'HomeFilled', label: '首页' },
  { path: '/cart', icon: 'ShoppingCart', label: '购物车', badge: true },
  { path: '/order', icon: 'List', label: '订单' },
  // { path: '/user', icon: 'User', label: '我的' }
]);

const scrollY = ref(0);
let rafId = null;
let orderCount = ref()
// 侧边栏是否可见（用于动画效果）
const isVisible = ref(true);

// 判断当前路由是否激活
const isActive = (path) => {
  return route.path === path;
};

// 导航到指定路径
const navigateTo = (path) => {
  if (path !== route.path) {
    router.push(path);
  }
};

// 滚动到顶部
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

const handleScroll = () => {
  // 使用 requestAnimationFrame 优化性能
  rafId = requestAnimationFrame(() => {
    scrollY.value = window.scrollY;
  });
};
const getCartCount = async () => {
  try {
    let res = await getCartCountApi()
    orderCount.value = res.data
  } catch (error) {
    ElMessage.error('获取订单数据失败');
  }
}
onMounted(() => {
  window.addEventListener('scroll', handleScroll);
  getCartCount()
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
  if (rafId) cancelAnimationFrame(rafId);
});
</script>

<style lang="scss" scoped>
li {
  cursor: pointer;
}
</style>